//
//  MusicViewController.m
//  AriseSamePro
//
//  Created by 包日守 on 15/10/31.
//  Copyright © 2015年 Arise. All rights reserved.
//

#import "MusicViewController.h"
#import "ARPlayerControl.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "ARAudioPlayDefault.h"
#import "ARAudioCell.h"
#import "ARMusicCell.h"
#import "ARGlobalInterface.h"
#import "ARCate5Model.h"

@interface MusicViewController ()<ARMusicCellDelegate,AVAudioPlayerDelegate,UIScrollViewDelegate>
@property (nonatomic,weak) ARPlayerControl *playerControl;
@end

@implementation MusicViewController


- (void) createPlayControl
{
        if (self.playerControl == nil) {
                
                NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"ARPlayerControl" owner:nil options:nil];
                ARPlayerControl *playerControl = [array lastObject];
                
                _playerControl = playerControl;
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 55)];
                
                [self.navigationController.view addSubview:playerControl];
                
                playerControl.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 55);
                
                self.tableView.tableHeaderView = view;
                [self.playerControl viewRefrash];
                
                
                self.playerControl.refleshTableView = self.tableView;
            self.playerControl.playButton.selected = NO;
            
        }
    [self.playerControl viewCreate];
    
            

}

- (ARPlayerControl *) playerControl
{
    if (_playerControl == nil) {
        
        ARAudioPlayDefault *audioDefault = [ARAudioPlayDefault defaultAudioPlay];
        if (audioDefault.isPlay && [audioDefault.playingCate.channelModel.index isEqualToString:self.index]) {
            
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"ARPlayerControl" owner:nil options:nil];
            ARPlayerControl *playerControl = [array lastObject];
            
            _playerControl = playerControl;
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 55)];
            // view.backgroundColor = [UIColor blueColor];
            
            
            [self.navigationController.view addSubview:playerControl];
            
            playerControl.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 55);
            
            self.tableView.tableHeaderView = view;
            [self.playerControl viewRefrash];
            
            
            self.playerControl.refleshTableView = self.tableView;
            
            
        }
        
        
        
    }
    return _playerControl;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     [self.playerControl viewRefrash];
    
    ARAudioPlayDefault *audioDefault = [ARAudioPlayDefault defaultAudioPlay];
    
    if (audioDefault.player != nil && [audioDefault.playingCate.channelModel.index isEqualToString:self.index] && audioDefault.isPlay) {
        self.playerControl.playButton.selected = audioDefault.isPlay;
    }
    else{
        self.playerControl.playButton.selected = NO;
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    ARCate5Model *model = self.cateModels[indexPath.section];
    CGFloat w = [UIScreen mainScreen].bounds.size.width - 25;
    CGRect centextRect = [model.txt boundingRectWithSize:CGSizeMake(w, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
    
    //NSLog(@"%lf",centextRect.size.height);
    //NSLog(@"%@",model.txt);
    
    if ([model.txt isEqualToString:@""]) {
        return  290 - 21;
    }
    
    
    return centextRect.size.height + 290 - 21;
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ARMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ARMusicCell"];
    
    if (cell == nil) {
        
        
        [tableView registerNib:[UINib nibWithNibName:@"ARMusicCell" bundle:nil] forCellReuseIdentifier:@"ARMusicCell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"ARMusicCell"];
        
    }
    cell.delegate = self;
    cell.cateModel = self.cateModels[indexPath.section];
    
    
    [cell setShareBtnBlock:^(ARCate5Model *cateModel, UIButton *sender) {
        [self createShare:cateModel WithSender:sender];
        
    }];
    
    return cell;


}



#pragma mark - MusicDelegate
- (void) musicCell:(ARMusicCell *)musicCell WithCateModel:(ARCate5Model *)cateModel
{
    self.playerControl.playButton.selected = !self.playerControl.playButton.selected;
    [self createPlayControl];
    //[self.playerControl viewRefrash];
    ARAudioPlayDefault *audioDefault = [ARAudioPlayDefault defaultAudioPlay];

    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    
    if ([audioDefault.MusicPath isEqualToString:[ARGlobalInterface musicTempCachePathWithMusicPath:cateModel.mediaModel.musicModel.src]]) {

        
        audioDefault.isPlay = YES;
        [audioDefault.player play];
        [self.tableView reloadData];
        return;
    }
    [audioDefault.player stop];
    
    NSString *filePath = [ARGlobalInterface musicTempCachePathWithMusicPath:cateModel.mediaModel.musicModel.src];
    
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSURL *url =[NSURL URLWithString:cateModel.mediaModel.musicModel.src];
        
        
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData * audioData;
            audioData = [NSData dataWithContentsOfURL:url];
            [audioData writeToFile:filePath atomically:YES];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self readyToPlay:filePath WithCate:cateModel];
            });
            
            
            
        });
        
        
        
    }
    else
    {
        [self readyToPlay:filePath WithCate:cateModel];
        
    }
    
    [self.tableView reloadData];
    
    
}


- (void) readyToPlay:(NSString *)filePath WithCate:(ARCate5Model *) cateModel
{
    
    
    
    ARAudioPlayDefault *audioDefault = [ARAudioPlayDefault defaultAudioPlay];
    
    [audioDefault.timer invalidate];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    audioDefault.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    [audioDefault.player prepareToPlay];
    [audioDefault.player setVolume:1];
    audioDefault.player.numberOfLoops = -1;
    [audioDefault.player play];
    
    
    //信息录入
    audioDefault.isPlay = YES;
    audioDefault.playingCate = cateModel;
    audioDefault.duration = [NSNumber numberWithInteger:audioDefault.player.duration];
    audioDefault.title = cateModel.mediaModel.musicModel.title;
    audioDefault.author = cateModel.mediaModel.musicModel.author;
    audioDefault.MusicPath = filePath;
    
    [audioDefault addCateModel:cateModel];
    
    audioDefault.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playProgress)userInfo:nil repeats:YES];
    
    [self.playerControl viewRefrash];
    
    [self.tableView reloadData];
    [self configNowPlayingInfoCenter];
    
    
    
    self.playerControl.playButton.selected = audioDefault.isPlay;
    
    
}

- (void) musicCellPause
{
    self.playerControl.playButton.selected = !self.playerControl.playButton.selected;
    
}

- (void)playProgress
{
    ARAudioPlayDefault * audioDefault = [ARAudioPlayDefault defaultAudioPlay];
    
    
    self.playerControl.progressVeiw.progress = (float)audioDefault.player.currentTime/audioDefault.duration.floatValue;
    self.playerControl.playDotConstraint.constant = 13+ self.playerControl.progressVeiw.progress * 320;
    
}

#pragma mark - 后台控制器

-(void)configNowPlayingInfoCenter{
    
    
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        
        
        ARAudioPlayDefault *audioDefault = [ARAudioPlayDefault defaultAudioPlay];
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        [dict setObject:audioDefault.playingCate.mediaModel.musicModel.title forKey:MPMediaItemPropertyTitle];
        
        [dict setObject:audioDefault.playingCate.mediaModel.musicModel.author forKey:MPMediaItemPropertyAlbumTitle];
        
        
        [dict setObject:[NSNumber numberWithInt:(int)audioDefault.player.duration] forKey:MPMediaItemPropertyPlaybackDuration];
        [dict setObject: [NSNumber numberWithInt:1] forKey:MPNowPlayingInfoPropertyPlaybackRate];
        
        
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:audioDefault.playingCate.mediaModel.musicModel.cover]]];
        
        // NSLog(@"--------%@",_musicImag);
        
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        
        [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
        
        
        [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
        
        
    }
    
    
    
}


- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    
    
    
    ARAudioPlayDefault *audioDefault =[ARAudioPlayDefault defaultAudioPlay];
    
    if (audioDefault.isPlay) {
        audioDefault.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playProgress)userInfo:nil repeats:YES];
    }
    
    
    
    
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    //[self resignFirstResponder];
    
    
    [self.playerControl removeFromSuperview];
    
    
    ARAudioPlayDefault *audioDefault =[ARAudioPlayDefault defaultAudioPlay];
    [audioDefault.timer invalidate];
    
    
    
    
}

- (BOOL) canBecomeFirstResponder
{
    
    return  YES;
}


- (void) remoteControlReceivedWithEvent:(UIEvent *)event
{
    
    
    //[self configNowPlayingInfoCenter];
    
    if (event.type == UIEventTypeRemoteControl) {
        ARAudioPlayDefault *audioDefault = [ARAudioPlayDefault defaultAudioPlay];
        
        switch (event.subtype) {
                
            case UIEventSubtypeRemoteControlTogglePlayPause:
                
                NSLog(@"stop!");
                
                //[self playAndStopSong:self.playButton];
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:{
                NSLog(@"stop!!");
                //[self playLastButton:self.lastButton];
                
                [audioDefault toLastSong];
                [self.playerControl viewRefrash];
                self.playerControl.playButton.selected = YES;
                audioDefault.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playProgress)userInfo:nil repeats:YES];
                [self configNowPlayingInfoCenter];
                [self.tableView reloadData];
                
                
                break;
            }
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"stop!!!");
                //[self playNextSong:self.nextButton];
                [audioDefault toNextSong];
                [self.playerControl viewRefrash];
                self.playerControl.playButton.selected = YES;
                audioDefault.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playProgress)userInfo:nil repeats:YES];
                [self configNowPlayingInfoCenter];
                [self.tableView reloadData];
                break;
                
            case UIEventSubtypeRemoteControlPlay:
                NSLog(@"stop!!!!");
                //[self playAndStopSong:self.playButton];
                
                
                if (!audioDefault.isPlay) {
                    [audioDefault startMusic];
                    self.playerControl.playButton.selected  = YES;
                }else
                {
                    [audioDefault pauseMusic];
                    self.playerControl.playButton.selected  = NO;
                }
                [self.tableView reloadData];
                break;
                
            case UIEventSubtypeRemoteControlPause:
                NSLog(@"stop!!!!!");
                //[self playAndStopSong:self.playButton];
                
                if (!audioDefault.isPlay) {
                    [audioDefault startMusic];
                    self.playerControl.playButton.selected  = YES;
                }else
                {
                    [audioDefault pauseMusic];
                    self.playerControl.playButton.selected  = NO;
                }
                [self.tableView reloadData];
                break;
                
            default:
                break;
        }
    }
    
    
    
}

#pragma mark - scrollViewDelegate
- (void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    [super scrollViewDidScroll:scrollView];
    //NSLog(@"%lf",scrollView.contentOffset.y);
    
    if (scrollView.contentOffset.y < 0) {
        self.playerControl.frame = CGRectMake(0, 64 - scrollView.contentOffset.y, [UIScreen mainScreen].bounds.size.width, 55);
    }
    else
    {
        self.playerControl.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 55);
        
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
